<?php
	class CSVWriter {
	
		private $csvFile;
		private $useMD5;
		private $delimiter;
		
		private $buffer;

		public function __construct($csvFile, $useMD5 = true, $delimiter = '|') {
			$this->csvFile 		= $csvFile;
			$this->useMD5 		= $useMD5;
			$this->delimiter	= $delimiter;
			$this->buffer		= '';
		}				
		
		public function setData($arrInput, $arrHeader = false) {
			$maxFields = 0;
			$this->buffer = '';
			if (is_array($arrHeader)) {
				$i = 0;
				foreach ($arrHeader as $header) {
					if ($i > 0)
						$this->buffer .= '|';
					$this->buffer .= $header;
					$i++;
				}
				$this->buffer .= "\n";
			}
			foreach ($arrInput as $inputs) {
				if ($maxFields == 0)
					$maxFields = count($inputs);
				$i = 1;
				foreach ($inputs as $input) {
					$this->buffer .= str_replace("\n", ' ', $input) . (($i < $maxFields) ? $this->delimiter : '');
					$i++;
				}
				$this->buffer .= "\n";
			}
			
			if ($this->useMD5) {
				$strMD5 = md5($this->buffer);
				$this->buffer .= $strMD5;
			}
		}
		
		public function getData() {
			return $this->buffer;
		}
		
		public function saveData() {
			return file_put_contents($this->csvFile, $this->buffer);
		}
		
	}
	// End of file.